<template>
  <div class="user-address-container">
    <h2 class="page-title">收货地址</h2>
    
    <div class="address-list" v-loading="loading">
      <!-- 添加新地址按钮 -->
      <el-button type="primary" icon="el-icon-plus" class="add-address-btn" @click="addAddress">
        添加新地址
      </el-button>
      
      <!-- 空状态 -->
      <div class="empty-state" v-if="addresses.length === 0 && !loading">
        <el-empty description="暂无收货地址" :image-size="200">
          <el-button type="primary" @click="addAddress">添加地址</el-button>
        </el-empty>
      </div>
      
      <!-- 地址列表 -->
      <div v-else class="address-cards">
        <el-card v-for="address in addresses" :key="address.id" class="address-card" shadow="hover">
          <div class="address-content">
            <div class="address-info">
              <div class="address-header">
                <span class="receiver">{{ address.receiver }}</span>
                <span class="phone">{{ address.phone }}</span>
                <el-tag size="small" type="success" v-if="address.isDefault === 1">默认</el-tag>
              </div>
              
              <div class="address-location">
                {{ getFullAddress(address) }}
              </div>
            </div>
            
            <div class="address-actions">
              <el-button type="text" @click="editAddress(address)">编辑</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button type="text" @click="deleteAddress(address)">删除</el-button>
              <el-divider direction="vertical" v-if="address.isDefault !== 1"></el-divider>
              <el-button type="text" v-if="address.isDefault !== 1" @click="setDefault(address)">设为默认</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 地址表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="addressForm" :rules="rules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        
        <el-form-item label="所在地区">
          <div class="region-selector">
            <div v-if="regionInputMode" class="manual-input-mode">
              <el-row :gutter="10">
                <el-col :span="8">
                  <el-input v-model="addressForm.province" placeholder="省份"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input v-model="addressForm.city" placeholder="城市"></el-input>
                </el-col>
                <el-col :span="8">
                  <el-input v-model="addressForm.district" placeholder="区/县"></el-input>
                </el-col>
              </el-row>
            </div>
            <div v-else>
              <el-cascader
                v-model="selectedRegion"
                :options="regionOptions"
                @change="handleRegionChange"
                placeholder="请选择所在地区">
              </el-cascader>
            </div>
            <div class="switch-mode">
              <el-link type="primary" @click="toggleRegionInputMode">
                {{ regionInputMode ? '使用地区选择器' : '手动输入地区' }}
              </el-link>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input type="textarea" v-model="addressForm.detailAddress" placeholder="请输入详细地址，如道路、门牌号、小区、楼栋号、单元等"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddress" :loading="saving">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAddressList, addAddress, updateAddress, deleteAddress, setDefaultAddress } from '@/api/address'
import { regionData } from '@/utils/region'

export default {
  name: 'UserAddress',
  data() {
    return {
      // 地址列表
      addresses: [],
      // 加载状态
      loading: false,
      saving: false,
      
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加收货地址',
      
      // 地址表单
      addressForm: {
        id: null,
        userId: null,
        receiver: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      
      // 选中的地区（用于级联选择器）
      selectedRegion: [],
      
      // 地区数据
      regionOptions: regionData,
      
      // 表单验证规则
      rules: {
        receiver: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          { max: 20, message: '姓名长度不能超过20个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
          { max: 100, message: '详细地址不能超过100个字符', trigger: 'blur' }
        ]
      },

      // 当前用户信息
      currentUser: null,

      // 地区输入模式
      regionInputMode: false
    }
  },
  created() {
    // 从sessionStorage获取用户信息
    this.currentUser = JSON.parse(sessionStorage.getItem('user') || '{}')
    this.fetchAddresses()
  },
  methods: {
    // 获取地址列表
    fetchAddresses() {
      if (!this.currentUser || !this.currentUser.id) return
      
      this.loading = true
      
      getAddressList(this.currentUser.id)
        .then(response => {
          if (response.code === 200) {
            this.addresses = response.data
          } else {
            this.$message.error(response.message || '获取地址列表失败')
          }
        })
        .catch(error => {
          console.error('获取地址列表失败', error)
          this.$message.error('获取地址列表失败，请稍后再试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 添加新地址
    addAddress() {
      this.resetAddressForm()
      this.dialogTitle = '添加收货地址'
      this.dialogVisible = true
    },
    
    // 编辑地址
    editAddress(address) {
      this.addressForm = {
        id: address.id,
        userId: address.userId,
        receiver: address.receiver,
        phone: address.phone,
        province: address.province,
        city: address.city,
        district: address.district,
        detailAddress: address.detailAddress,
        isDefault: address.isDefault === 1
      }
      
      // 尝试设置级联选择器的值
      const hasAllRegions = address.province && address.city && address.district
      if (hasAllRegions) {
        // 检查是否能在regionOptions中找到对应的值
        this.selectedRegion = [address.province, address.city, address.district]
        // 默认使用级联选择器模式
        this.regionInputMode = false
      } else {
        // 如果地址中的地区信息不完整，使用手动输入模式
        this.regionInputMode = true
      }
      
      this.dialogTitle = '编辑收货地址'
      this.dialogVisible = true
    },
    
    // 保存地址
    saveAddress() {
      // 检查地区信息
      if (!this.regionInputMode) {
        // 级联选择器模式，检查是否选择了地区
        if (this.selectedRegion.length < 3) {
          this.$message.warning('请选择完整的所在地区')
          return
        }
        // 更新表单中的地区信息
        this.addressForm.province = this.selectedRegion[0]
        this.addressForm.city = this.selectedRegion[1]
        this.addressForm.district = this.selectedRegion[2]
      } else {
        // 手动输入模式，检查是否填写了地区
        if (!this.addressForm.province || !this.addressForm.city || !this.addressForm.district) {
          this.$message.warning('请填写完整的省市区信息')
          return
        }
      }

      this.$refs.addressForm.validate(valid => {
        if (valid) {
          this.saving = true
          
          // 构建请求数据
          const addressData = {
            ...this.addressForm,
            userId: this.currentUser.id,
            isDefault: this.addressForm.isDefault ? 1 : 0
          }
          
          // 判断是新增还是编辑
          const request = addressData.id ? updateAddress(addressData) : addAddress(addressData)
          
          request
            .then(response => {
              if (response.code === 200) {
                this.$message.success(addressData.id ? '地址修改成功' : '地址添加成功')
                this.dialogVisible = false
                this.fetchAddresses()
              } else {
                this.$message.error(response.message || (addressData.id ? '地址修改失败' : '地址添加失败'))
              }
            })
            .catch(error => {
              console.error(addressData.id ? '地址修改失败' : '地址添加失败', error)
              this.$message.error((addressData.id ? '地址修改' : '地址添加') + '失败，请稍后再试')
            })
            .finally(() => {
              this.saving = false
            })
        }
      })
    },
    
    // 删除地址
    deleteAddress(address) {
      this.$confirm('确定要删除该收货地址吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAddress(address.id, this.currentUser.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('地址删除成功')
              this.fetchAddresses()
            } else {
              this.$message.error(response.message || '地址删除失败')
            }
          })
          .catch(error => {
            console.error('地址删除失败', error)
            this.$message.error('地址删除失败，请稍后再试')
          })
      }).catch(() => {})
    },
    
    // 设为默认地址
    setDefault(address) {
      setDefaultAddress(address.id, this.currentUser.id)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('默认地址设置成功')
            this.fetchAddresses()
          } else {
            this.$message.error(response.message || '默认地址设置失败')
          }
        })
        .catch(error => {
          console.error('默认地址设置失败', error)
          this.$message.error('默认地址设置失败，请稍后再试')
        })
    },
    
    // 处理地区变化
    handleRegionChange(value) {
      if (value && value.length >= 3) {
        this.addressForm.province = value[0]
        this.addressForm.city = value[1]
        this.addressForm.district = value[2]
      }
    },
    
    // 重置地址表单
    resetAddressForm() {
      this.addressForm = {
        id: null,
        userId: this.currentUser ? this.currentUser.id : null,
        receiver: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      }
      this.selectedRegion = []
      // 默认使用级联选择器模式
      this.regionInputMode = false
      
      // 如果表单已经创建，则重置验证
      if (this.$refs.addressForm) {
        this.$refs.addressForm.clearValidate()
      }
    },
    
    // 获取完整地址
    getFullAddress(address) {
      const parts = [
        address.province,
        address.city,
        address.district,
        address.detailAddress
      ].filter(Boolean)
      
      return parts.join(' ')
    },

    // 切换地区输入模式
    toggleRegionInputMode() {
      this.regionInputMode = !this.regionInputMode
    }
  }
}
</script>

<style scoped>
.user-address-container {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #333;
}

.add-address-btn {
  margin-bottom: 20px;
}

.address-cards {
  margin-top: 20px;
}

.address-card {
  margin-bottom: 15px;
  border-radius: 8px;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-header {
  margin-bottom: 10px;
}

.receiver {
  font-size: 16px;
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  color: #666;
  margin-right: 15px;
}

.address-location {
  color: #333;
  line-height: 1.5;
}

.address-actions {
  margin-left: 20px;
}

.empty-state {
  margin-top: 50px;
  text-align: center;
}

.region-selector {
  width: 100%;
}

.manual-input-mode {
  width: 100%;
  margin-bottom: 10px;
}

.switch-mode {
  margin-top: 10px;
  text-align: right;
  font-size: 13px;
}
</style> 